/**
 * <p>Copyright:Copyright(c) 2019</p>
 * <p>Company:Professional</p>
 * <p>Package:ces.org.course.event</p>
 * <p>File:FileUploadListener.java</p>
 * <p>类更新历史信息</p>
 * @todo chanlong(陈龙) 创建于 May 17, 2019 4:24:21 PM
 */
package ces.org.course.api.event;

import java.io.File;
import java.nio.file.Paths;

import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import ces.org.course.api.entity.DictionaryEntity;
import ces.org.course.api.service.DictionaryService;
import ces.org.course.api.watch.FileListener;
import ces.org.course.api.watch.FileListener.FileListenerBuilder;
import cn.hutool.core.io.FileUtil;
import lombok.AllArgsConstructor;
import lombok.Builder;

/**
 * <p>描述: </p>
 * <p>Company: Professional</p>
 * @author chanlong(陈龙)
 * @date May 17, 2019 4:24:21 PM
 * @version 1.0.2019
 */
@Component
@Builder @AllArgsConstructor
public class FileUploadListener {

	@EventListener()
	public void listener(final FileUploadEvent event) {
		System.out.println("字典触发模式：event");
		onFileCreate(Paths.get(event.getMessage().getFilePath()).toFile());
	}
	 // 文件创建时触发
	public void onFileCreate(final File file) {
		service.put(DictionaryEntity.CACHE_KEY, file);
	}

	 // 文件删除时触发
	public void onFileDelete(final File file) {
		service.clear(DictionaryEntity.CACHE_KEY);
		
		FileUtil.loopFiles(file.getParentFile()).forEach(f -> {
			if (null != f && "xml".equals(FileUtil.extName(f))) service.put(DictionaryEntity.CACHE_KEY, f);	
		});
	}

	// 文件修改时触发
	public void onFileChange(final File file) {
		service.put(DictionaryEntity.CACHE_KEY, file);
	}
	
	private DictionaryService service;
	
}
